<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="login-header">
          <SvgIcon name="yujing" size="50px" class="cursor-pointer" />
          <h2 style="margin: 0;">天气预警</h2>
        </div>
      </template>

      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        class="login-form"
      >
        <el-form-item label="" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item label="" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            @click="handleLogin"
            :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { User, UserInfo } from '@/types/user.ts';
  import SvgIcon from '@/components/SvgIcon.vue';

  interface LoginForm {
    username: string;
    password: string;
  }

  const router = useRouter();
  const loginFormRef = ref();
  const loading = ref(false);

  const loginForm = reactive<LoginForm>({
    username: '',
    password: '',
  });

  const loginRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
    ],
  };

  const handleLogin = async () => {
    if (!loginFormRef.value) return;

    const valid = await loginFormRef.value.validate();
    if (!valid) return;

    loading.value = true;

    // 从 public 目录读取 users.json
    try {
      let userList: User | null;
      const response = await fetch('/users.json');
      userList = await response.json();

      const user = userList?.users?.find((u: UserInfo) =>
        u.username === loginForm.username && u.password === loginForm.password,
      ) || null;

      if (user) {
        localStorage.setItem('isLoggedIn', 'true');
        localStorage.setItem('username', loginForm.username);
        ElMessage.success('登录成功！');
        router.push('/');
      } else {
        ElMessage.error('用户名或密码错误！');
      }
    } catch (error) {
      ElMessage.error('登录失败，请稍后重试！');
      console.error('读取用户数据失败:', error);
    } finally {
      loading.value = false;
    }
  };
</script>

<style lang="scss" scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    /*linear-gradient：创建线性渐变背景
    135deg：渐变角度为135度（从左上角到右下角的方向）
    #667eea 0%：渐变起始颜色是蓝色调（#667eea），从0%位置开始
    #764ba2 100%：渐变结束颜色是紫红色调（#764ba2），到100%位置结束*/
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .login-card {
    width: 400px;

    .login-header {
      text-align: center;
      color: #333;
      display: flex;
      align-items: center;
      gap: 10px;
      justify-content: center
    }

    .login-form {
      margin-top: 20px;
    }

    .login-button {
      width: 100%;
    }
  }
</style>